extends CharacterBody2D # 角色基础类，继承自 Godot 的 CharacterBody2D

@export var move_speed: float = 100.0 # 移动速度
@export var max_health: float = 100.0 # 最大生命值
@export var attack_damage: float = 10.0 # 攻击伤害
@export var attack_interval: float = 1.0 # 攻击间隔（秒）
@export var self_group: String = "" # 自身分组名称
@export var target_group: String = "" # 目标分组名称
@export var tracking_radius: float = 300.0 # 追踪半径
@export var stop_distance: float = 10.0 # 停止距离

var current_health: float = 0.0 # 当前生命值
var attack_timer: float = 0.0 # 攻击计时器
var target: Node2D # 当前锁定目标

func _ready() -> void: # 初始化函数
	current_health = max_health
	if self_group != "":
		add_to_group(self_group)

func _physics_process(delta: float) -> void: # 物理帧处理
	# 更新攻击冷却计时器
	attack_timer = max(0.0, attack_timer - delta)
	
	# 更新追踪目标
	_update_target()
	if target == null:
		return
		
	# 执行移动逻辑
	_move_to_target()
	move_and_slide()

func _move_to_target() -> void: # 朝目标移动（支持导航代理或直线移动）
	if target == null:
		velocity = Vector2.ZERO
		return
	
	var nav_agent: NavigationAgent2D = get_node_or_null("NavigationAgent2D")
	
	if nav_agent:
		# 方案A：使用导航代理（可避开障碍物）
		nav_agent.target_position = target.global_position
		
		if nav_agent.is_navigation_finished():
			# 已到达目标位置，停止移动
			velocity = Vector2.ZERO
		else:
			# 沿路径点移动
			var next_point: Vector2 = nav_agent.get_next_path_position()
			velocity = (next_point - global_position).normalized() * move_speed
	else:
		# 方案B：备用直线移动（无导航节点时）
		var distance: float = global_position.distance_to(target.global_position)
		
		if distance <= stop_distance:
			# 距离目标足够近，停止移动
			velocity = Vector2.ZERO
		else:
			# 直线朝目标移动
			velocity = (target.global_position - global_position).normalized() * move_speed




func _update_target() -> void: # 更新目标 寻找距离最近目标（目标分组）
	if target_group == "":
		return
	var nodes: Array[Node] = get_tree().get_nodes_in_group(target_group)
	var nearest: Node2D = null
	var min_dist: float = tracking_radius
	for n in nodes:
		if n is Node2D and n != self and is_instance_valid(n):
			var d: float = global_position.distance_to((n as Node2D).global_position)
			if d <= tracking_radius and d < min_dist:
				min_dist = d                                       
				nearest = n
	target = nearest

func attack() -> void: # 尝试攻击
	if attack_timer > 0.0 or target == null or not is_instance_valid(target):
		return
	attack_timer = max(attack_interval, 0.01)


func get_damage(amount: float, _source: Node = null) -> void: # 应用伤害
	current_health = max(0.0, current_health - amount)
	if current_health <= 0.0:
		die()

func die() -> void: # 死亡处理
	queue_free()
